package com.example.arithmeticleetcode.leetcode.dec;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * @program: arithmetic-leetcode
 * @description:
 * @author: FangZhen
 * @create: 2020-12-22 09:31
 **/
public class Demo20 {

    public static void main(String[] args) {
        TreeNode root = new TreeNode(3);
        TreeNode rootLeft = new TreeNode(9);
        TreeNode rootRight = new TreeNode(20);
        TreeNode rootRightLeft = new TreeNode(15);
        TreeNode rootRightRight = new TreeNode(7);
        root.left = rootLeft;
        root.right = rootRight;
        rootRight.left = rootRightLeft;
        rootRight.right = rootRightRight;
        System.out.println(new Demo20().zigzagLevelOrder(root));
    }

    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List<List<Integer>> lists = new ArrayList<>();
        if (root == null) return lists;
        List<TreeNode> treeNodes = new ArrayList<>();
        treeNodes.add(root);
        zigzagLevelOrder(lists, treeNodes, true);
        return lists;
    }

    private void zigzagLevelOrder(List<List<Integer>> lists, List<TreeNode> treeNodes, boolean leftFlag) {
        if (treeNodes == null || treeNodes.isEmpty()) return;
        List<Integer> list = new ArrayList<>();
        List<TreeNode> nodeList = new ArrayList<>();
        int len = treeNodes.size();
        int index = len - 1;
        for (int i = 0; i < len; i++) {
            TreeNode node = treeNodes.get(i);
            if (node.left != null) nodeList.add(node.left);
            if (node.right != null) nodeList.add(node.right);
            //true左
            int val = leftFlag ? node.val : treeNodes.get(index--).val;
            list.add(val);
        }
        lists.add(list);
        zigzagLevelOrder(lists, nodeList, !leftFlag);
    }


}

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode() {
    }

    TreeNode(int x) {
        val = x;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}
